import { defineEventHandler, getCookie } from 'h3';
import { getDbConnection } from '../../utils/db.js';

export default defineEventHandler(async (event) => {
  try {
    const sessionCookie = getCookie(event, 'session');
    if (!sessionCookie) {
      return { authenticated: false };
    }

    let session;
    try {
      session = JSON.parse(sessionCookie);
    } catch (error) {
      console.error('Failed to parse session cookie:', error);
      return { authenticated: false };
    }

    if (!session?.userId) {
      return { authenticated: false };
    }

    const db = await getDbConnection();
    const user = await db.get(
      'SELECT id, username, name FROM users WHERE id = ?',
      [session.userId]
    );

    if (!user) {
      return { authenticated: false };
    }

    return {
      authenticated: true,
      user,
    };
  } catch (error) {
    console.error('auth/me error:', error);
    return { authenticated: false };
  }
});
